<template>
	<view class="device_name_layout">
		<view class="top">
			<view class="headImg" @click="chooseImage">
				<image :src="imagePath" mode="aspectFill"></image>
			</view>
			<view class="input-name">
				<input class="name" value="" placeholder-style="color:#999" :placeholder="$t('deviceNameHead.name')"
					@input="changeNameContent" />
			</view>
		</view>

		<view class="confirm-btn" @click="confirm">
			{{$t('deviceNameHead.confirm')}}
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		i18nTool
	} from '../../utils/i18en';
	import {
		apiSetDeviceHeadImg,
		apiSetDeviceName
	} from '../../api/device_api';
	import {onLoad} from "@dcloudio/uni-app";
import { getImei } from '../../utils/user_tools';
	var deviceName;
	const param = {}
	let imei = getImei();
	param.imei = imei
	const imagePath = ref("../../static/device/upload_head.png")
	const tempFilePath = ref(null);
	onLoad(()=>{
		uni.setNavigationBarTitle({
			title:i18nTool("deviceNameHead.navTitle")
		})
	})

	const chooseImage = () => {
		uni.chooseImage({
			count: 1, //默认9
			crop: {
				width: 40,
				height: 40,
				quality: 80,

			},
			sourceType: ['album'], //从相册选择
			success: res => {
				// chooseImageSuccess(res)
				tempFilePath.value = res.tempFilePaths[0];
				imagePath.value = res.tempFilePaths[0];
				param.filePath = tempFilePath.value;
			}
		});
	}
	
	const setDeviceHeadImg = async () => {
		if (param.filePath == null) {
			uni.showToast({
				title: i18nTool('deviceNameHead.noHeadImgHint'),
				icon: "none",
			})
			return;
		}
		param.filePath = tempFilePath.value;
		let res = await apiSetDeviceHeadImg(param);
		uni.navigateBack();
	}
	
	function changeNameContent(e) {
		deviceName = e.detail.value;
	}

	async function confirm() {
		if (deviceName == null) {
			uni.showToast({
				title: i18nTool('deviceNameHead.noNameHint'),
				icon: "none",
			})
			return;
		}
		
		uni.showLoading({
			title:"loading...",
			mask:true,
		})
		param.dvName = deviceName;
		param.imei = imei;
		let res = await apiSetDeviceName(param);
		uni.hideLoading();
		setDeviceHeadImg();
	}
</script>

<style lang="scss" scoped>
	.device_name_layout {

		.top {
			padding: 100rpx 40rpx;
			display: flex;
			align-items: center;

			.headImg {
				width: 120rpx;
				height: 120rpx;
				border-radius: 50%;

				image {
					width: 100%;
					height: 100%;
					border-radius: 50%;
				}
			}

			.input-name {
				padding-left: 20rpx;
				border-bottom: 2rpx solid #f1f1f1;
				height: 100rpx;
				margin-right: 10rpx;
				flex-grow: 1;

				.name {
					width: 100%;
					height: 100%;
				}
			}
		}

		.confirm-btn {
			margin-left: 30rpx;
			margin-right: 30rpx;
			margin-top: 60rpx;
			height: 80rpx;
			color: #fff;
			background-color: #53786C;
			border-radius: 40rpx;
			@include flex-box-set(center);

		}
	}
</style>